package one.stand.service;

import one.stand.advice.ResultEnum;
import one.stand.event.PlatformChildAddEvent;
import one.stand.mapper.CompanyPlatformChildMapper;
import one.stand.mapper.CompanyPlatformMapperApiCrmPcExt;
import one.stand.model.Company;
import one.stand.model.CompanyPlatform;
import one.stand.model.CompanyPlatformChild;
import one.stand.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CompanyPlatformServiceImpl implements CompanyPlatformService {
    @Autowired
    private CompanyPlatformMapperApiCrmPcExt companyPlatformMapperApiCrmPcExt;
    @Autowired
    private CompanyPlatformChildMapper companyPlatformChildMapper;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    @Transactional
    public void add(Integer type, Integer companyId) {
        Company company = companyBaseService.getById(companyId);
        AssertUtil.nonNull(company, ResultEnum.PARAM_CHECK);

        CompanyPlatform companyPlatform = new CompanyPlatform();
        companyPlatform.setType(type);
        companyPlatform.setCompanyId(companyId);
        companyPlatform.setCompanyKey(company.getCompanyKey());
        companyPlatformMapperApiCrmPcExt.insertSelective(companyPlatform);

        setChild(companyPlatform.getId(), companyId);

        applicationContext.publishEvent(new PlatformChildAddEvent(companyId));
    }

    @Override
    @Transactional
    public void addChild(Integer id, Integer companyId) {
        CompanyPlatform companyPlatform = companyPlatformMapperApiCrmPcExt.selectByPrimaryKey(id);
        AssertUtil.nonNull(companyPlatform, ResultEnum.PARAM_CHECK, "平台不存在");
        companyPlatform = companyPlatformMapperApiCrmPcExt.selectByCompanyId(companyId);
        AssertUtil.isNull(companyPlatform, ResultEnum.PARAM_CHECK, "已设为平台，不能再加入其他平台");

        companyPlatformMapperApiCrmPcExt.deleteChildByCompanyId(companyId);

        setChild(id, companyId);

        applicationContext.publishEvent(new PlatformChildAddEvent(companyId));
    }

    @Override
    @Transactional
    public void remove(Integer id) {
        CompanyPlatform companyPlatform = companyPlatformMapperApiCrmPcExt.selectByPrimaryKey(id);
        AssertUtil.nonNull(companyPlatform, ResultEnum.PARAM_CHECK);

        companyPlatformMapperApiCrmPcExt.deleteByPrimaryKey(id);
        companyPlatformMapperApiCrmPcExt.deleteChild(id);
    }

    private void setChild(Integer id, Integer companyId) {
        CompanyPlatformChild companyPlatformChild = new CompanyPlatformChild();
        companyPlatformChild.setPlatformId(id);
        companyPlatformChild.setCompanyId(companyId);
        companyPlatformChildMapper.insertSelective(companyPlatformChild);
    }
}
